﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CoreApp.DBAccess;
using CoreApp.DBModel;
using CoreApp.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace CoreApp.Web.Controllers
{
    [Authorize]
    public class ArticleController : ParentController
    {
        private readonly IArticleRepository articleRepository;
        private readonly IHostingEnvironment hostingEnvironment;
        public ArticleController(IArticleRepository _articleRepository, IHostingEnvironment _hostingEnvironment)
        {
            articleRepository = _articleRepository;
            hostingEnvironment = _hostingEnvironment;
        }

        #region 博客列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>        
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> GetArticleList()
        {
            //查询所有
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("userid", base.GetUserId().ToString());
            var list = await articleRepository.GetListByParams(dic);

            return PartialView("Partial_ArticleList", list);
        }
        #endregion

        #region 发布博客
        /// <summary>
        /// 发布
        /// </summary>
        /// <returns></returns>
        public IActionResult Post()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ArticlePost()
        {
            var articlename = Request.Form["articlename"];
            var articlecontent = Request.Form["articlecontent"];

            //简单验证
            if (string.IsNullOrWhiteSpace(articlename))
            {
                return Json(new { code = "failed", msg = "标题不能为空" });
            }
            if (string.IsNullOrWhiteSpace(articlecontent))
            {
                return Json(new { code = "failed", msg = "内容不能为空" });
            }

            ArticleInfo articleEntity = new ArticleInfo();
            articleEntity.UserId = base.GetUserId();
            articleEntity.AddTime = DateTime.Now;
            articleEntity.Name = articlename;
            articleEntity.Contents = articlecontent;
            int result = await articleRepository.InsertArticle(articleEntity);
            if (result > 0)
                return Json(new { code = "success", msg = "登陆成功" });
            else
                return Json(new { code = "failed", msg = "登陆失败" });
        }
        #endregion

        #region 编辑博客
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            var entity = await articleRepository.QueryArticle(id);

            return View(entity);
        }

        [HttpPost]
        public async Task<IActionResult> ArticleEdit()
        {
            var articleid = Request.Form["articleid"];
            var articlename = Request.Form["articlename"];
            var articlecontent = Request.Form["articlecontent"];

            //简单验证
            int _id = 0;
            if (!int.TryParse(articleid, out _id))
                return Json(new { code = "failed", msg = "标识ID不正确" });

            if (string.IsNullOrWhiteSpace(articlename))
                return Json(new { code = "failed", msg = "标题不能为空" });

            if (string.IsNullOrWhiteSpace(articlecontent))
                return Json(new { code = "failed", msg = "内容不能为空" });

            var entity = await articleRepository.QueryArticle(_id);
            if (entity == null)
                return Json(new { code = "failed", msg = "博客不存在" });

            //编辑
            entity.Name = articlename;
            entity.Contents = articlecontent;
            int result = await articleRepository.UpdateArticle(entity);
            if (result > 0)
                return Json(new { code = "success", msg = "编辑成功" });
            else
                return Json(new { code = "failed", msg = "编辑失败" });
        }
        #endregion

        #region 博客详情
        public async Task<IActionResult> Detail(int id)
        {
            var entity = await articleRepository.QueryArticle(id);

            return View(entity);
        }
        #endregion

        #region 删除博客
        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelteArticle()
        {
            var id = Request.Form["id"];
            int _id = 0;
            if (!int.TryParse(id, out _id))
                return Json(new { code = "failed", msg = "标识ID不正确" });

            int result = await articleRepository.DeleteArticleById(_id);
            if (result > 0)
                return Json(new { code = "success", msg = "删除成功" });
            else
                return Json(new { code = "failed", msg = "删除失败" });
        }
        #endregion

        #region 导出Excel
        [HttpPost]
        public async Task<IActionResult> ExportExcel1()
        {
            DataSet ds = await GetDataSet();
            if (ds == null)
                return Json(new { code = "failed", msg = "暂无数据" });

            //通过注入IHostingEnvironment服务对象获取Web根目录的绝对路径
            string webRootPath = hostingEnvironment.WebRootPath;
            //excel文件存放文件夹
            string fileDirectory = "/excel";
            //excel保存路径
            string fileSavePath = webRootPath + fileDirectory;
            if (!Directory.Exists(fileSavePath))
            {
                //目录不存在则新建目录
                Directory.CreateDirectory(fileSavePath);
            }
            //文件名称
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
            //文件完整路径
            string filePath = Path.Combine(fileSavePath, fileName);

            //导出excel
            bool isOk = EPPlusHelper.ExportExcel(ds, filePath, true);
            if (isOk)
            {
                //html页面直接window.location.href='/excel/20190325195219495.xlsx'; 即可下载
                return Json(new { code = "success", msg = fileDirectory + "/" + fileName });
            }
            else
                return Json(new { code = "failed", msg = "导出失败" });
        }

        [HttpGet]
        public async Task<IActionResult> ExportExcel2()
        {
            DataSet ds = await GetDataSet();
            if (ds == null)
                return Content("暂无数据");

            //通过注入IHostingEnvironment服务对象获取Web根目录的绝对路径
            string webRootPath = hostingEnvironment.WebRootPath;
            //excel文件存放文件夹
            string fileDirectory = "/excel";
            //excel保存路径
            string fileSavePath = webRootPath + fileDirectory;
            if (!Directory.Exists(fileSavePath))
            {
                //目录不存在则新建目录
                Directory.CreateDirectory(fileSavePath);
            }
            //文件名称
            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
            //文件完整路径
            string filePath = Path.Combine(fileSavePath, fileName);

            //导出excel
            bool isOk = EPPlusHelper.ExportExcel(ds, filePath, true);
            if (isOk)
            {
                return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", fileName);
            }
            else
                return Content("导出失败");
        }

        private async Task<DataSet> GetDataSet()
        {
            //查询所有
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("userid", base.GetUserId().ToString());
            var list = await articleRepository.GetListByParams(dic);

            if (list == null || list.Count == 0)
                return null;

            //创建DataSet
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            //表名
            dt.TableName = "博客列表";
            dt.Columns.Add("标题");
            dt.Columns.Add("发布时间");

            //表头
            DataRow headers = dt.NewRow();
            headers["标题"] = "标题";
            headers["发布时间"] = "发布时间";
            dt.Rows.Add(headers);

            //其他行
            foreach (ArticleInfo item in list)
            {
                DataRow dr = dt.NewRow();
                dr["标题"] = item.Name;
                dr["发布时间"] = item.AddTime;

                dt.Rows.Add(dr);
            }

            ds.Tables.Add(dt);

            return ds;
        }
        #endregion

        #region 导入Excel
        public IActionResult Import()
        {
            return View();
        }

        [HttpPost]
        //用vscode编辑器在浏览器运行没问题，
        //用vs编辑器在谷歌浏览器没问题，360浏览器直接奔溃，进入不了下面方法（这不是重点，这问题不管了）
        public async Task<IActionResult> ImportExcel()
        {
            try
            {
                var files = Request.Form.Files;
                if (files.Count > 0)
                {
                    IFormFile file = files[0];
                    if (files.Count > 0)
                    {
                        //文件的后缀验证这里省略

                        //通过注入IHostingEnvironment服务对象获取Web根目录的绝对路径
                        string webRootPath = hostingEnvironment.WebRootPath;

                        //excel文件存放文件夹
                        string fileDirectory = "/excel";
                        //excel保存路径
                        string fileSavePath = webRootPath + fileDirectory;
                        if (!Directory.Exists(fileSavePath))
                        {
                            //目录不存在则新建目录
                            Directory.CreateDirectory(fileSavePath);
                        }
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx";
                        string filePath = Path.Combine(fileSavePath, fileName);
                        //把流写入到路径为filePath的文件中
                        using (FileStream fs = new FileStream(filePath, FileMode.Create))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }

                        //导入excel
                        FileInfo newFile = new FileInfo(filePath);//获取上面写入的文件
                        if (newFile.Length > 0)
                        {
                            DataSet ds = EPPlusHelper.ImportExcel(newFile, true);
                            if (ds != null && ds.Tables.Count > 0)
                            {
                                foreach (DataTable dt in ds.Tables)
                                {
                                    int rowCount = dt.Rows.Count;
                                    for (int row = 0; row < rowCount; row++)
                                    {
                                        ArticleInfo articleEntity = new ArticleInfo();
                                        articleEntity.AddTime = DateTime.Now;
                                        articleEntity.UserId = base.GetUserId();
                                        articleEntity.Name = dt.Rows[row][0].ToString();
                                        articleEntity.Contents = dt.Rows[row][1].ToString();
                                        await articleRepository.InsertArticle(articleEntity);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }

            return Redirect("/Article/Index");
        }
        #endregion
    }
}